<template>
  <div class="categories">
    <div class="title">{{ pageInfo.name }} Categories - apkuick</div>
    <GoogleAdCollect
      id="6164837103"
      adm-id="div-gpt-ad-1747196057474-0"
      name="APK_Categories_Display_1"
      parent-page="Categories"
      @adSuccess="handleAdSuccess"
      @adError="handleAdError"
  />
    <div class="category-list">
      <div 
        v-for="(item, index) in categories" 
        :key="index" 
        @click="handleCategoryClick(item)"
        class="category-item"
      >
        <svg-icon :name="item.slug" />
        <div class="name">{{  item.name  }}</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import GoogleAdCollect from '@/components/GoogleAdCollect.vue'
import { ref, onMounted } from 'vue'
import { homeParams } from '~/utils/homeParams'

const props = defineProps({
  categories: {
    type: Array,
    required: true
  },
  pageInfo: {
    type: Object,
    required: true
  }
})

// 存储所有分类的 URL
const categoryUrls = ref(new Map())

const generateCategoryUrls = () => {
  if (!process.client) return

  props.categories.forEach(item => {
    const queryParams = {
      type: props.pageInfo.type,
      name: encodeURIComponent(item.name),
      ...homeParams()
    }
    categoryUrls.value.set(item.slug, `/categories/${item.slug}?${new URLSearchParams(queryParams).toString()}`)
  })
}

// 在组件挂载后生成所有 URL
onMounted(() => {
  generateCategoryUrls()
})

const handleCategoryClick = (item) => {
  const url = categoryUrls.value.get(item.slug)
  if (url) {
    window.location.href = url
  }
}

const handleAdSuccess = () => {
  console.log('广告加载成功')
}

const handleAdError = () => {
  console.log('广告加载失败')
}
</script>

<style scoped lang="scss">
.categories {
  .title {
    @include title;
  }
  .category-list {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 1rem;
    margin-top: 1rem;
    @media screen and (max-width: 768px) {
      grid-template-columns: 1fr;
    }
    .category-item {
      text-align: center;
      border: 1px solid #FFECDE;
      height: 48px;
      display: flex;
      align-items: center;
      gap: 1rem;
      padding: 0 16px;
      border-radius: 3px;
      font-size: 16p;
      background: #FFFAF4;
      border-radius: 4px;
      text-decoration: none;
      cursor: pointer;
      &:hover {
        background: #FFF5E6;
      }
      .svg-icon {
        width: 24px;
        height: 24px;
        color: #F78B17FF;
      }
      .name {
        font-size: 0.9rem;
        color: #333;
      }
    }
  }
}
</style>